// User.js
import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Col, Row } from 'antd';
import ActivityListABI from '../contract/ABIs/ActivityList.json'; // 活动列表合约 ABI
import MaterialListABI from '../contract/ABIs/MaterialList.json'; // 材料列表合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI 
import UserABI from '../contract/ABIs/User.json'; // 用户合约 ABI

import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js'; // 活动列表合约地址
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress.js'; // 材料列表合约地址
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
import UserNavBar from './nav/UserNavBar.js';
import gb from '../static/bootstrap/images/gb.svg';
import us from '../static/bootstrap/images/us.svg';
import user3 from '../static/bootstrap/images/user3.png';
import Head from './nav/Head.js';


const User = () => {
    const [web3, setWeb3] = useState(null);
    const { address } = useParams();
    const [contractActivityList, setcontractActivityList] = useState(null);
    const [contractMaterialList, setcontractMaterialList] = useState(null);
    const [contractUserList, setContractUserList] = useState(null);
    const [contractUser, setcontractUser] = useState(null);
    const [isUser, setisUser] = useState(false);
    const [userName, setUserName] = useState('');
    const [idNumber, setIdNumber] = useState('');
    const [password, setPassword] = useState('');
    const [passwordAgain, setPasswordAgain] = useState('');

    const [userInfo, setUserInfo] = useState([]);
    const [IsList, setIsList] = useState(false); // 控制是否显示列表
    const navigate = useNavigate();

    useEffect(() => {
        async function init() {
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    const activityListInstance = new web3Instance.eth.Contract(
                        ActivityListABI,
                        ActivityListAddress
                    );
                    setcontractActivityList(activityListInstance);

                    const materialListInstance = new web3Instance.eth.Contract(
                        MaterialListABI,
                        MaterialListAddress
                    );
                    setcontractMaterialList(materialListInstance);

                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);

                    const userInstance = new web3Instance.eth.Contract(
                        UserABI,
                        address
                    );
                    setcontractUser(userInstance);

                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    const ownerAddress = await userInstance.methods.getUserAddr().call();
                    setisUser(currentAddress === ownerAddress);

                    await GetOwneInfo(web3Instance, userInstance);
                    const userInfoResult = await userInstance.methods.getOwnerInfo().call();

                    if (userInfoResult) {
                        setUserName(userInfoResult[0] || ''); // 第一个元素是用户名
                        setIdNumber(userInfoResult[2] || ''); // 第二个元素是学号
                    }
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);

    const GetOwneInfo = async (web3Instance, userInstance) => {
        if (userInstance) {
            try {
                const accounts = await web3Instance.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress);

                const result = await userInstance.methods.getUserInfo().call({ from: fromAddress });
                console.log("用户信息:", result);

                const userInfoArray = [result];
                setUserInfo(userInfoArray);
                setIsList(true); // 让列表显示出来
            } catch (error) {
                console.error(error);
                alert("查询失败");
            }
        }
    };

    const passwordsMatch = () => {
        return password === passwordAgain;
    };

    const modifyPassword = async () => {
        try {
            const accounts = await web3.eth.getAccounts();
            const fromAddress = accounts[0];
            console.log("fromAddress:", fromAddress, "Input:", password, passwordAgain);

            if (!password && !passwordAgain) {
                alert('请填写所有字段再进行修改！');
                return;
            }

            if (!passwordsMatch()) {
                alert('两次输入的密码不匹配，请重新输入！');
                return;
            } else {
                await contractUser.methods.modifyPassword(password).send({ from: fromAddress });
            }

            alert('用户信息修改成功，请重新登录！');
            navigate('/');
        } catch (error) {
            console.error('Error updating user information:', error);
            alert('用户信息修改失败！');
        }
    };

    return (
        <div>
            {!isUser && (<div>您没有权限访问此页面。</div>)}

            {isUser && (
                <div className="page-wrapper" style={{
                    backgroundColor: '#FFFFFF'
                }}>
                    <div className="main-container">
                        <UserNavBar address={address} />

                        <div className="app-container">
                            <Head></Head>
                            <div className="app-body">
                                <div className="container-fluid">

                                    <div>
                                        <main className="page hire-me-page">
                                            <section className="portfolio-block hire-me">

                                                <div className="container">
                                                    <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                                        data-bs-theme="light"
                                                        style={{ backgroundColor: 'rgba(36, 36, 41, 0.6)' }}
                                                    >
                                                        <Row gutter={[16, 16]}>
                                                            <Col span={8}>
                                                                <Card title={<span style={{ color: 'black' }}>个人信息</span>}>
                                                                    {IsList ? (
                                                                        userInfo.map((user) => (
                                                                            <div key={user.idNumber}>
                                                                                <p style={{ color: 'black' }}>真实姓名:{user.realName}</p>
                                                                                <p style={{ color: 'black' }}>身份证号:{user.idNumber}</p>
                                                                                <p style={{ color: 'black' }}>学号:{user.studentIDNumber}</p>
                                                                                <p style={{ color: 'black' }}>班级:{user.classNumber}</p>
                                                                                <p style={{ color: 'black' }}>学历:
                                                                                    {parseInt(user.educationalLevel) === 1 ? '本科' :
                                                                                        parseInt(user.educationalLevel) === 2 ? '专科' :
                                                                                            parseInt(user.educationalLevel) === 3 ? '研究生' :
                                                                                                parseInt(user.educationalLevel) === 4 ? '博士' : ''}
                                                                                </p>
                                                                                <p style={{ color: 'black' }}>
                                                                                    年级:
                                                                                    {parseInt(user.gradeLevel) === 1 ? '大一' :
                                                                                        parseInt(user.gradeLevel) === 2 ? '大二' :
                                                                                            parseInt(user.gradeLevel) === 3 ? '大三' :
                                                                                                parseInt(user.gradeLevel) === 4 ? '大四' : ''}
                                                                                </p>
                                                                                <p style={{ color: 'black' }}>积分:{user.nowPoint.toString()}</p>
                                                                                <p style={{ color: 'black' }}>学分：{user.nowCredit.toString()}</p>
                                                                                <p style={{ color: 'black' }}>性别：{user.gender ? '男' : '女'}</p>
                                                                                <p style={{ color: 'black' }}>电话号码：{user.phone}</p>
                                                                                <p style={{ color: 'black' }}>密码：{user.password}</p>
                                                                            </div>
                                                                        ))
                                                                    ) : (
                                                                        <p>暂无用户信息。</p>
                                                                    )}
                                                                </Card>
                                                            </Col>
                                                            <Col span={16}>
                                                                <Card title={<span style={{ color: 'black' }}>更改密码</span>}>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="realName" style={{ color: 'black' }}>真实姓名</label>
                                                                        <input className="form-control item" id="realName" type="text" placeholder="真实姓名" disabled value={userName} onChange={(e) => setUserName(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="studentID" style={{ color: 'black' }}>学号</label>
                                                                        <input className="form-control item" id="studentID" type="text" placeholder="学号" disabled value={idNumber} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="password" style={{ color: 'black' }}>密码</label>
                                                                        <input className="form-control item" id="password" type="password" placeholder="密码" value={password} onChange={(e) => setPassword(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="passwordAgain" style={{ color: 'black' }}>再次确认密码</label>
                                                                        <input className="form-control item" id="passwordAgain" type="password" placeholder="再次确认密码" value={passwordAgain} onChange={(e) => setPasswordAgain(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3 mt-4">
                                                                        <button className="btn btn-primary btn-lg d-block w-100" onClick={modifyPassword}>修改</button>
                                                                    </div>
                                                                </Card>
                                                            </Col>
                                                        </Row>
                                                    </div>
                                                </div>

                                            </section>
                                        </main>
                                    </div>


                                </div>
                            </div>
                            <div className="app-footer">
                                <span>
                                    © Bootstrap Gallery 2023
                                </span>
                            </div>
                        </div>
                    </div>

                </div>
            )}
        </div>
    );
}

export default User;
